package cn.oowoo.rabbitmq.priority;

import cn.oowoo.rabbitmq.config.RabbitConfig;
import com.rabbitmq.client.*;
import lombok.SneakyThrows;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

/**
 * @Author ZhangBin
 * @Date 2021/5/8 13:48
 * @Description: 简单消息发送-消费者
 * 演示时，先启动生产者产生消息，再启动消费者。如果先启动消费者消费速度过快，看不出优先级
 **/
public class PriorityConsumer {

    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = RabbitConfig.createConnection();
        // 创建消息通道
        Channel channel = connection.createChannel();

        // 创建消费者
        Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String msg = new String(body, "UTF-8");
                System.out.println("Received message : " + msg+"优先级："+properties.getPriority());
                channel.basicAck( envelope.getDeliveryTag(),true);
            }
        };

        /**
         * autoAck= false :关闭自动确认，也就是开启手动确认
         * 开始获取消息，注意这里开启了手工应答（关闭自动应答）
         * String basicConsume(String queue, boolean autoAck, Consumer callback)
         *
         */
        channel.basicConsume(RabbitConfig.QUEUE_PRIORITY_NAME, false,consumer);//测试优先级
        //channel.basicConsume(RabbitConfig.QUEUE_NORMAL_NAME, false,consumer); //无优先级


    }

}
